package com.heima.article.service.impl;

import com.heima.article.service.ArticleInfoService;
import com.heima.article.thread.AppThreadLocalUtil;
import com.heima.common.cache.CacheService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ArticleInfoServiceImpl implements ArticleInfoService {

    @Autowired
    private CacheService cacheService;
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        //0.参数判空
        if (dto==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //1.获取参数
        Long articleId = dto.getArticleId();
        Integer authorId = dto.getAuthorId();

        ApUser user = AppThreadLocalUtil.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST,"用户不存在");
        }
        Integer userId = user.getId();
        //2判断状态
        boolean islike=false,isunlike=false,iscollection=false,isfollow=false;
       //2.1喜欢
        Object likeBehavior = cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + articleId, userId.toString());
        if(likeBehavior!=null){
            islike=true;
        }
        //2.2不喜欢
        Object unlikeBehavior = cacheService.hGet(BehaviorConstants.UN_LIKE_BEHAVIOR + articleId, userId.toString());
        if(unlikeBehavior!=null){
            isunlike=true;
        }
        //2.3收藏
        Object collectionBehavior = cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + articleId, userId.toString());
        if(collectionBehavior!=null){
            iscollection=true;
        }
        //2.4关注
        Double followScore = cacheService.zScore(BehaviorConstants.APUSER_FOLLOW_RELATION + userId, authorId);
        System.out.println(followScore);
        if(followScore!=null){
            isfollow=true;
        }
        //3.组装
        Map<String,Object> resultMap =new HashMap<>(4);
        resultMap.put("isfollow", isfollow);
        resultMap.put("islike", islike);
        resultMap.put("isunlike", isunlike);
        resultMap.put("iscollection", iscollection);

        return ResponseResult.okResult(resultMap);
    }
}
